<template>
  <div>
    <table>
      <thead>
        <tr>
          <th v-for="(v, i) in columns" :key="i">
            {{ v.name }}
            <span
              class="arrow"
              v-show="v.hasOwnProperty('isAsc')"
              :class="v.isAsc ? 'asc' : 'dsc'"
              @click="sortFn(v)"
            ></span>
          </th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="(v, i) in NewList" :key="i">
          <td v-for="(item, index) in columns" :key="index">
            {{ v[item.name] }}
          </td>
        </tr>
      </tbody>
    </table>
  </div>
</template>

<script>
export default {
  props: ["columns", "date", "val"],
  methods: {
    sortFn(item) {
      if (!item.hasOwnProperty("isAsc")) {
        return;
      } else {
        item.isAsc = !item.isAsc;
      }
      console.log(typeof this.date[0][item.name]);
      if (typeof this.date[0][item.name] == "string") {
        // console.log(item.isAsc);
        if (item.isAsc) {
          this.date.sort((v, i) => {
            if (v[item.name].charAt(0) > i[item.name].charAt(0)) {
              return 1;
            } else if (v[item.name].charAt(0) < i[item.name].charAt(0)) {
              return -1;
            } else if (v[item.name].charAt(0) == i[item.name].charAt(0)) {
              return 0;
            }
          });
        } else {
          this.date.reverse();
        }
      }
      if (typeof this.date[0][item.name] == "number") {
        if (item.isAsc) {
          this.date.sort((v, i) => {
            return v[item.name] - i[item.name];
          });
        } else {
          this.date.reverse();
        }
      }
    },
  },
  computed: {
    NewList() {
      if (!this.val) {
        return this.date;
      } else {
        return this.date.filter((val) => {
          return val.name.toUpperCase().indexOf(this.val.toUpperCase()) != -1;
        });
      }
    },
  },
};
</script>

<style scoped>
</style>